package com.luhuiguo.cms.server.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.beanutils.converters.LongConverter;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Text;
import com.luhuiguo.cms.server.converter.BlobConverter;
import com.luhuiguo.cms.server.converter.TextConverter;

public class MapperUtils {

    static {
        ConvertUtils.register(new DateConverter(null), Date.class);
        ConvertUtils.register(new LongConverter(null), Long.class);
        ConvertUtils.register(new TextConverter(), Text.class);
        ConvertUtils.register(new TextConverter(), String.class);
        ConvertUtils.register(new BlobConverter(), Blob.class);
        ConvertUtils.register(new BlobConverter(), byte[].class);
    }

    public static <T> T map(Object source, Class<T> destinationClass) {
        if (null == source) {
            return null;
        }
        try {
            Constructor<T> constructor = destinationClass.getDeclaredConstructor();
            T dest = constructor.newInstance();

            BeanUtils.copyProperties(dest, source);
            return dest;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static void map(Object source, Object destination) {
        if (null == source) {
            return;
        }
        try {
            BeanUtils.copyProperties(destination, source);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    public static <T> List<T> mapList(List<?> source, Class<T> destinationClass) {
        if (null == source) {
            return null;
        }
        List<T> list = new ArrayList<T>();
        for (Object obj : source) {
            list.add(map(obj, destinationClass));
        }
        return list;
    }
}
